package logic

import (
	"context"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"k8s.io/apimachinery/pkg/util/json"
	"shops/model/mysql"
	"shops/model/redis"
	"shops/shoprpc/internal/svc"
	"shops/shoprpc/shoprpc"
	"strconv"
	"time"
)

type ListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListLogic {
	return &ListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ListLogic) List(in *shoprpc.ListRequest) (*shoprpc.ListResponse, error) {
	// todo: add your logic here and delete this line
	page := in.Page
	if page <= 0 {
		page = 1
	}
	pageSize := in.Size
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}
	offset := (page - 1) * pageSize
	name := in.Name
	var list []mysql.Product
	get := redis.Rdb.Get("list" + strconv.Itoa(int(offset)) + name)
	if get.Val() == "" {
		tx := mysql.DB.Debug().Order("price desc").Offset(int(offset)).Limit(int(pageSize))
		if name != "" {
			tx.Where("name like ?", "%"+in.Name+"%").Find(&list)
		}
		tx.Debug().Find(&list)
		marshal, _ := json.Marshal(&list)
		redis.Rdb.Set("list"+strconv.Itoa(int(offset))+name, marshal, time.Hour*24)
	} else {
		json.Unmarshal([]byte(get.Val()), &list)
	}
	fmt.Println(list)
	var lists []*shoprpc.List
	for _, product := range list {
		s := shoprpc.List{
			Name:   product.Name,
			Price:  float32(product.Price),
			Num:    int64(product.Num),
			Image:  product.Image,
			Intro:  product.Intro,
			UserId: int64(product.UserId),
			Id:     int64(product.ID),
		}
		lists = append(lists, &s)
	}
	fmt.Println(lists)
	return &shoprpc.ListResponse{List: lists}, nil
}
